package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class ModifyStationListActivity extends ListActivity{
	private ArrayList<JSONObject> json_list;
	private ArrayList<StationItem> list;
	private StationItemAdapter nadapter;
	private ImageButton ok;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.modify_station_list);
		json_list = new ArrayList<JSONObject>();
		list = new ArrayList<StationItem>();
		ok = (ImageButton)findViewById(R.id.btnOk);

		ok.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		setFavoriteList();
	}

	private void setFavoriteList(){
		Intent intent = getIntent();
		String result = intent.getExtras().get("modify_list").toString();
		JSONArray json_arr;
		try {
			json_arr = new JSONArray(result);
			for(int i = 0 ; i < json_arr.length(); i++){
				JSONObject json_obj = (JSONObject) json_arr.get(i);
				json_list.add(json_obj);
			}
			Collections.sort(json_list, myComparator);
			for(int i = 0 ; i < json_list.size() ; i++){
				JSONObject station = json_list.get(i);
				list.add(new StationItem(station.get("name").toString(), station.get("station_id").toString()));
			}
			nadapter = new StationItemAdapter(getBaseContext(), R.layout.modify_station_row, list);
		    ListView lv = getListView();
		    lv.setAdapter(nadapter);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
    private final static Comparator<JSONObject> myComparator= new Comparator<JSONObject>() {
        private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
        	try {
				return collator.compare(object1.get("name"), object2.get("name"));
			} catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
		}
    };

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}
	}
	
	private class StationItemAdapter extends ArrayAdapter<StationItem>{
		private ArrayList<StationItem> items;
		private int layout;
		
		public StationItemAdapter(Context ctx, int rsrcId, ArrayList<StationItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			final StationItem e = items.get(position);
			if(e != null){
				((TextView)v.findViewById(R.id.stationName)).setText(e.getName());
				((ImageButton)v.findViewById(R.id.btnDelete)).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						list.remove(position);
						UploadAsynkTask task = new UploadAsynkTask();
						String[] params = new String[]{ ServerURL.deleteFavoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
									"station_id", e.getId()};
						
						task.execute(params);
						nadapter.notifyDataSetChanged();
					}
				});
			}
			return v;
		}
	}

	private class StationItem{
		private String station_name;
		private String station_id;
		
		private StationItem(String name, String id){
			station_name = name;
			station_id = id;
		}
		private String getName(){
			return station_name;
		}
		private String getId(){
			return station_id;
		}
		
	}
}
